package com.google.gwt.homepage.smile.client;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.homepage.smile.client.event.AddContactEvent;
import com.google.gwt.homepage.smile.client.event.AddContactEventHandler;
import com.google.gwt.homepage.smile.client.event.ContactUpdatedEvent;
import com.google.gwt.homepage.smile.client.event.ContactUpdatedEventHandler;
import com.google.gwt.homepage.smile.client.event.EditContactEvent;
import com.google.gwt.homepage.smile.client.event.EditContactEventHandler;
import com.google.gwt.homepage.smile.client.event.EditContactCancelledEvent;
import com.google.gwt.homepage.smile.client.event.EditContactCancelledEventHandler;
import com.google.gwt.homepage.smile.client.presenter.EnneagramFeaturesPresenter;
import com.google.gwt.homepage.smile.client.presenter.ContactsPresenter;
import com.google.gwt.homepage.smile.client.presenter.EditContactPresenter;
import com.google.gwt.homepage.smile.client.presenter.EnneagramStatisticsPresenter;
import com.google.gwt.homepage.smile.client.presenter.EnneagramTestPresenter;
import com.google.gwt.homepage.smile.client.presenter.SajuTestPresenter;
import com.google.gwt.homepage.smile.client.presenter.Presenter;
import com.google.gwt.homepage.smile.client.presenter.SearchFriendPresenter;
import com.google.gwt.homepage.smile.client.view.EnneagramFeaturesView;
import com.google.gwt.homepage.smile.client.view.ContactsView;
import com.google.gwt.homepage.smile.client.view.EditContactView;
import com.google.gwt.homepage.smile.client.view.EnneagramStatisticsView;
import com.google.gwt.homepage.smile.client.view.EnneagramTestView;
import com.google.gwt.homepage.smile.client.view.SajuTestView;
import com.google.gwt.homepage.smile.client.view.SearchFriendView;


import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.homepage.smile.client.Application;
import com.google.gwt.homepage.smile.shared.BannerSajuInfo;
import com.google.gwt.homepage.smile.shared.FriendTable;
import com.google.gwt.homepage.smile.shared.MemberBean;
import com.google.gwt.homepage.smile.shared.SajuData;
import com.google.gwt.homepage.smile.shared.SajuDataTable;
import com.google.gwt.http.client.UrlBuilder;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.LocaleInfo;



import com.google.gwt.resources.client.ImageResource;


import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TabBar;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;

public class AppController implements Presenter, ValueChangeHandler<String> {
  private final HandlerManager eventBus;
  private final SmileServiceAsync rpcService; 
  private HasWidgets container;
  
  //HorizontalPanel hPanel = new HorizontalPanel();
  //Tree menu = new Tree();
  //FlowPanel contentsPanel = new FlowPanel();
  
  private Application app = new Application();
  
  
  HTML currentTime=null;//현재시간 배너
  private static final int TIME_REFRESH_INTERVAL = 500; // ms
  
  HTML ohhang=null;//사주결과 배너
  private static final int SAJU_REFRESH_INTERVAL = 60000; // ms
  
  HTML insertBirth=null;//사주정보입력 배너
  
  
  HTML loginBtn=null;//배너에 로그인 버튼
  
  Button searchFriendBtn=null;//친구찾기 버튼
  /**
   * A mapping of history tokens to their associated menu items.
   */
  private Map<String, TreeItem> itemTokens = new HashMap<String, TreeItem>();
  
  /**
   * A mapping of menu items to the Page(History token) display when the item is selected.
   */
  private Map<TreeItem, String> itemWidgets = new HashMap<TreeItem, String>();
  
  
  
  /**
   * The static images used throughout the Homepage.
   */
  public static final SmileImages images = (SmileImages) GWT.create(SmileImages.class);
  
  
  
 //Create the constants
  SmileConstants constants = (SmileConstants) GWT.create(SmileConstants.class);
  
  public AppController(SmileServiceAsync rpcService, HandlerManager eventBus) {
	  
	
	  
    this.eventBus = eventBus;
    this.rpcService = rpcService;
    
    
    // Create the application
    setupMainLinks();
    setupTitlePanel();
    setupBannerPanel();
    setupOptionsPanel();
    setupMainMenu();
    
    
    // Setup timer to refresh  TIME automatically.
    Timer refreshTimeTimer = new Timer() {
      @Override
      public void run() {
        refreshCurrentTime();
      }
    };
    refreshTimeTimer.scheduleRepeating(TIME_REFRESH_INTERVAL);
    
    
    
 // Setup timer to refresh  SAJU automatically.
    Timer refreshSajuTimer = new Timer() {
      @Override
      public void run() {
        refreshSajuInfo();
      }
    };
    refreshSajuTimer.scheduleRepeating(SAJU_REFRESH_INTERVAL);
    
    
    
    // Add a handler that sets the content widget when a menu item is selected
    app.addSelectionHandler(new SelectionHandler<TreeItem>() {
      public void onSelection(SelectionEvent<TreeItem> event) {
        TreeItem item = event.getSelectedItem();
        
        //본문 설정
        String token = itemWidgets.get(item);
       // if (content != null && !content.equals(app.getContent())) {
          History.newItem(token);
        //}
        
      }
    });
    
    
    bind();
  }
  
  private void bind() {
    History.addValueChangeHandler(this);

    eventBus.addHandler(AddContactEvent.TYPE,
        new AddContactEventHandler() {
          public void onAddContact(AddContactEvent event) {
            doAddNewContact();
          }
        });  

    eventBus.addHandler(EditContactEvent.TYPE,
        new EditContactEventHandler() {
          public void onEditContact(EditContactEvent event) {
            doEditContact(event.getId());
          }
        });  

    eventBus.addHandler(EditContactCancelledEvent.TYPE,
        new EditContactCancelledEventHandler() {
          public void onEditContactCancelled(EditContactCancelledEvent event) {
            doEditContactCancelled();
          }
        });  

    eventBus.addHandler(ContactUpdatedEvent.TYPE,
        new ContactUpdatedEventHandler() {
          public void onContactUpdated(ContactUpdatedEvent event) {
            doContactUpdated();
          }
        });  
  }
  
  private void doAddNewContact() {
    History.newItem("add");
  }
  
  private void doEditContact(String id) {
    History.newItem("edit", false);
    Presenter presenter = new EditContactPresenter(rpcService, eventBus, new EditContactView(), id);
    //presenter.go(container);
    presenter.go(app.getContentContainer());
    
  }
  
  private void doEditContactCancelled() {
    History.newItem("list");
  }
  
  private void doContactUpdated() {
    History.newItem("list");
  }
  
  public void go(final HasWidgets container) {
    this.container = container;
    
    this.container.add(app);
    
    if ("".equals(History.getToken())) {
      History.newItem("saju_test");
    }
    else {
      History.fireCurrentHistoryState();
    }
  }

  public void onValueChange(ValueChangeEvent<String> event) {
	  
	  TreeItem item = itemTokens.get(event.getValue());
	  
	  if (item == null) {
          item = app.getMainMenu().getItem(0).getChild(0);  
	  }
	  
	  // Select the associated TreeItem
      app.getMainMenu().setSelectedItem(item, false);
      app.getMainMenu().ensureSelectedItemVisible();
      
      
      // Show the associated Contents
	  String token = event.getValue();
	    

	    if (token != null) {
	      Presenter presenter = null;
	      if (token.equals("enneagram_test")) {
	    	    app.setContentTitle(new HTML(constants.menu_1()));
		        presenter = new EnneagramTestPresenter(rpcService, eventBus, new EnneagramTestView(constants));
	      }
	      else if (token.equals("enneagram_features")) {
	    	    app.setContentTitle(new HTML(constants.menu_1()));
		        presenter = new EnneagramFeaturesPresenter(rpcService, eventBus, new EnneagramFeaturesView(constants));
	      }
	      else if (token.equals("enneagram_statistics")) {
	    	    app.setContentTitle(new HTML(constants.menu_1()));
		        presenter = new EnneagramStatisticsPresenter(rpcService, eventBus, new EnneagramStatisticsView());
	      }
	      else if (token.equals("saju_test")) {
	    	    app.setContentTitle(new HTML(constants.menu_3())); 
		        presenter = new SajuTestPresenter(rpcService, eventBus, new SajuTestView(constants));
	      }
	      else if (token.equals("search_friend")) {
	    	    app.setContentTitle(new HTML(constants.menu_3())); 
		        presenter = new SearchFriendPresenter(rpcService, eventBus, new SearchFriendView(constants));
	      }
	      else if (token.equals("join_member")) {
	    	  app.setContentTitle(new HTML(constants.menu_1()));
		        presenter = new EnneagramStatisticsPresenter(rpcService, eventBus, new EnneagramStatisticsView());
	      }
	      else if (token.equals("list")) {
	        presenter = new ContactsPresenter(rpcService, eventBus, new ContactsView());
	      }
	      else if (token.equals("add")) {
	        presenter = new EditContactPresenter(rpcService, eventBus, new EditContactView());
	      }
	      else if (token.equals("edit")) {
	        presenter = new EditContactPresenter(rpcService, eventBus, new EditContactView());
	      }
	      
	     
	      
	      if (presenter != null) {
	        //presenter.go(container);
	        presenter.go(app.getContentContainer());
	      }
	    }  
	  
	/*  
	String token = event.getValue();
    

    if (token != null) {
      Presenter presenter = null;

      if (token.equals("list")) {
        presenter = new ContactsPresenter(rpcService, eventBus, new ContactsView());
      }
      else if (token.equals("add")) {
        presenter = new EditContactPresenter(rpcService, eventBus, new EditContactView());
      }
      else if (token.equals("edit")) {
        presenter = new EditContactPresenter(rpcService, eventBus, new EditContactView());
      }
      
      if (presenter != null) {
        presenter.go(container);
      }
    }
    */
    
  }
  
  
  
  private void setupMainMenu() {
	    Tree mainMenu = app.getMainMenu();

	    
	    
	    TreeItem enneagram = mainMenu.addItem(constants.menu_1());
	    setupMainMenuOption(enneagram,constants.menu_1_1(),"enneagram_test",images.catWidgets());
	    setupMainMenuOption(enneagram,constants.menu_1_2(),"enneagram_features",images.catWidgets());
	    //setupMainMenuOption(enneagram,constants.menu_1_3(),"enneagram_statistics",images.catWidgets());
	    
	   
	    
	    
	    
	    //TreeItem mbti = mainMenu.addItem(constants.menu_2());
	    //setupMainMenuOption(mbti,constants.menu_2_1(),"MBTI_test",images.catWidgets());
	    //setupMainMenuOption(mbti,constants.menu_2_2(),"MBTI_features",images.catWidgets());
	    //setupMainMenuOption(mbti,constants.menu_2_3(),"MBTI_statistics",images.catWidgets());
	    
	    
	    
	    
	    
	    TreeItem saju = mainMenu.addItem(constants.menu_3());
	    setupMainMenuOption(saju,constants.menu_3_1(),"saju_test",images.catWidgets());
	    setupMainMenuOption(saju,constants.menu_3_2(),"search_friend",images.catWidgets());
	    //setupMainMenuOption(saju,constants.menu_3_3(),"saju_statistics",images.catWidgets());
	    
	    
	    
	    //TreeItem imsi = mainMenu.addItem("IMSI");
	    //setupMainMenuOption(imsi,"add","add",images.catWidgets());
	   
	    
	  }
  
  
  /**
   * Add an option to the main menu.
   * 
   * @param parent the {@link TreeItem} that is the option
   * @param content the {@link ContentWidget} to display when selected
   * @param image the icon to display next to the {@link TreeItem}
   */
  private void setupMainMenuOption(TreeItem parent, String childName, String token,
      ImageResource image) {
    // Create the TreeItem
    TreeItem option = parent.addItem(AbstractImagePrototype.create(image).getHTML()
        + " " + childName);

    // Map the item to its history token and History token
    itemTokens.put(token, option);
    itemWidgets.put(option,token);
  }
  
  
  /**
   * Create the title bar at the top of the application.
   */
  private void setupTitlePanel() {
    // Get the title from the internationalized constants
    //String pageTitle = "<h1><a href=\"/Smile.html\" >" + constants.mainTitle() + "</a></h1><h2>"
	  String pageTitle = "<h1>" + constants.mainTitle() + "</h1><h2>"
        + constants.mainSubTitle() + "</h2>";

    // Add the title and some images to the title bar
    HorizontalPanel titlePanel = new HorizontalPanel();
    titlePanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
    Image logoImg =new Image(images.gwtLogo());
    logoImg.addStyleName("logoImg");
    logoImg.addClickHandler(new ClickHandler() {   
	      public void onClick(ClickEvent event) {
	    	  Window.Location.assign("/");
	    	  //History.newItem("saju_test"); 
	      }
	    });
    titlePanel.add(logoImg);
    titlePanel.add(new HTML(pageTitle));

    app.setTitleWidget(titlePanel);
  }
  
  
  /**
   * Create the banner bar at the top of the application.
   */
  private void setupBannerPanel() {
    // Get the title from the internationalized constants
    //String pageTitle = "<h1>" + constants.mainTitle() + "</h1><h2>"
    //    + constants.mainSubTitle() + "</h2>";

    // Add the title and some images to the title bar
    HorizontalPanel titlePanel = new HorizontalPanel();
    titlePanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
    
    currentTime = new HTML("&nbsp;");
    currentTime.addStyleName("time");
    refreshCurrentTime();
    titlePanel.add(currentTime);
    
    ohhang = new HTML("&nbsp;");
    ohhang.setVisible(false);
    ohhang.addStyleName("link");
    
    ohhang.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
        	showDetailSaju();
            }
          }
        );
    ohhang.addMouseOverHandler(new MouseOverHandler(){
    	public void onMouseOver(MouseOverEvent event){
    		ohhang.removeStyleName("mouseDown");
    		ohhang.removeStyleName("mouseOut");
    		ohhang.addStyleName("mouseOver");
    	}
    });
    ohhang.addMouseOutHandler(new MouseOutHandler(){
    	public void onMouseOut(MouseOutEvent event){
    		ohhang.removeStyleName("mouseDown");
    		ohhang.removeStyleName("mouseOver");
    		ohhang.removeStyleName("mouseUp");
    		ohhang.addStyleName("mouseOut");
    	}
    });
  
    ohhang.addMouseDownHandler(new MouseDownHandler(){
    	public void onMouseDown(MouseDownEvent event){
    		ohhang.removeStyleName("mouseOver");
    		ohhang.removeStyleName("mouseOut");
    		ohhang.removeStyleName("mouseUp");
    		ohhang.addStyleName("mouseDown");
    	}
    });
    ohhang.addMouseUpHandler(new MouseUpHandler(){
    	public void onMouseUp(MouseUpEvent event){
    		ohhang.removeStyleName("mouseOver");
    		ohhang.removeStyleName("mouseOut");
    		ohhang.removeStyleName("mouseDown");
    		ohhang.addStyleName("mouseUp");
    	}
    });
    
    
    
    titlePanel.add(ohhang);
    
    insertBirth = new HTML("&nbsp;");
    insertBirth.setVisible(false);
    insertBirth.addStyleName("link");
    insertBirth.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
        	  showInsertBirth();
            }
          }
        );
    insertBirth.addMouseOverHandler(new MouseOverHandler(){
    	public void onMouseOver(MouseOverEvent event){
    		insertBirth.removeStyleName("mouseDown");
    		insertBirth.removeStyleName("mouseOut");
    		insertBirth.addStyleName("mouseOver");
    	}
    });
    insertBirth.addMouseOutHandler(new MouseOutHandler(){
    	public void onMouseOut(MouseOutEvent event){
    		insertBirth.removeStyleName("mouseDown");
    		insertBirth.removeStyleName("mouseOver");
    		insertBirth.removeStyleName("mouseDown");
    		insertBirth.addStyleName("mouseOut");
    	}
    });
    insertBirth.addMouseDownHandler(new MouseDownHandler(){
    	public void onMouseDown(MouseDownEvent event){
    		insertBirth.removeStyleName("mouseOver");
    		insertBirth.removeStyleName("mouseOut");
    		insertBirth.removeStyleName("mouseDown");
    		insertBirth.addStyleName("mouseDown");
    	}
    });
    insertBirth.addMouseUpHandler(new MouseUpHandler(){
    	public void onMouseUp(MouseUpEvent event){
    		insertBirth.removeStyleName("mouseOver");
    		insertBirth.removeStyleName("mouseOut");
    		insertBirth.removeStyleName("mouseDown");
    		insertBirth.addStyleName("mouseUp");
    	}
    });
    titlePanel.add(insertBirth);
    
    
    
    
    loginBtn = new HTML("&nbsp;");
    loginBtn.setVisible(false);
    loginBtn.addStyleName("link");
    /*loginBtn.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
        	  showInsertBirth();
            }
          }
        );*/
    loginBtn.addMouseOverHandler(new MouseOverHandler(){
    	public void onMouseOver(MouseOverEvent event){
    		loginBtn.removeStyleName("mouseDown");
    		loginBtn.removeStyleName("mouseOut");
    		loginBtn.addStyleName("mouseOver");
    	}
    });
    loginBtn.addMouseOutHandler(new MouseOutHandler(){
    	public void onMouseOut(MouseOutEvent event){
    		loginBtn.removeStyleName("mouseDown");
    		loginBtn.removeStyleName("mouseOver");
    		loginBtn.removeStyleName("mouseDown");
    		loginBtn.addStyleName("mouseOut");
    	}
    });
    loginBtn.addMouseDownHandler(new MouseDownHandler(){
    	public void onMouseDown(MouseDownEvent event){
    		loginBtn.removeStyleName("mouseOver");
    		loginBtn.removeStyleName("mouseOut");
    		loginBtn.removeStyleName("mouseDown");
    		loginBtn.addStyleName("mouseDown");
    	}
    });
    loginBtn.addMouseUpHandler(new MouseUpHandler(){
    	public void onMouseUp(MouseUpEvent event){
    		loginBtn.removeStyleName("mouseOver");
    		loginBtn.removeStyleName("mouseOut");
    		loginBtn.removeStyleName("mouseDown");
    		loginBtn.addStyleName("mouseUp");
    	}
    });
    titlePanel.add(loginBtn);
    
    
    searchFriendBtn=new Button("친구찾기");
    searchFriendBtn.setVisible(false);
    searchFriendBtn.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
	         //로그인이 되어있지 않으면 로그인을 하도록함
	      	  
	      	  //로그인 되어있으면 이메일을 가져와서 서버로 친구찾기 요청
	           	           
	            rpcService.getLoginInfo(Window.Location.getPath(), new AsyncCallback<MemberBean>() {
	      	      public void onSuccess(MemberBean result) {
	      	    	if(result.getEmail()!=null && result.getEmail().length()>0){ 
	      	    		requestSearchFriend(result.getEmail());
	      	    	}else{
	      	    		Window.alert("로그인하셔야 사용가능합니다.");
	      	    	}
	
	      	      }
	      	      public void onFailure(Throwable caught) {
	      	        Window.alert("Error getLoginInfo");
	      	      }
	      	    });
            }
          }
        );
    

    titlePanel.add(searchFriendBtn);
    
    refreshSajuInfo();
    
    app.setBannerWidget(titlePanel);
  }
  
  
  /*친구찾기 서버로 요청*/
  private void requestSearchFriend(String i_email){
	  rpcService.searchFriend(i_email, new AsyncCallback<List<FriendTable>>() {
	      public void onSuccess(List<FriendTable> result) {
	    	  showSearchFriendResult(result);
	      }
	      
	      public void onFailure(Throwable caught) {
	        Window.alert("Error getSearchFriend");
	      }
	    });
  }
  
  
  
  private void refreshCurrentTime(){
	  Date date = new Date();
	  DateTimeFormat activeFormat = DateTimeFormat.getFormat("yyyy-MM-dd(EEE) HH:mm:ss");
	  currentTime.setHTML(activeFormat.format(date));
  }
  
  
  private void refreshSajuInfo(){
	  //Date date = new Date();
	  //DateTimeFormat activeFormat = DateTimeFormat.getFormat("yyyy-MM-dd(EEE) HH:mm:ss");
	  //ohhang.setHTML(activeFormat.format(date));
	  
	  rpcService.getSajuBanner(Window.Location.getPath(), new AsyncCallback<BannerSajuInfo>() {
	      public void onSuccess(BannerSajuInfo result) {
	    	  if(result.getResult_code().equals("0")){//로그인이 않되어있을때
	    		  loginBtn.setHTML(result.getResult_val());
		    		ohhang.setVisible(false);
		    		searchFriendBtn.setVisible(false);
		    		insertBirth.setVisible(false);
		    		loginBtn.setVisible(true);
		      }else if(result.getResult_code().equals("1")){//saju정보가 없을때
	    		insertBirth.setHTML(result.getResult_val());
	    		ohhang.setVisible(false);
	    		searchFriendBtn.setVisible(false);
	    		loginBtn.setVisible(false);
	    		insertBirth.setVisible(true);
	    	  }else if(result.getResult_code().equals("2")){//saju정보가 있을때
	    		   ohhang.setHTML(result.getResult_val());
	    		   ohhang.setVisible(true);
		    		searchFriendBtn.setVisible(true);
		    		insertBirth.setVisible(false);
		    		loginBtn.setVisible(false);
		      }
	    	  /*
	    	if(result.getEmail()!=null && result.getEmail().length()>0){ 
	    		app.addLink(new HTML("<font style=\"color:#2D8F26;\">"+result.getEmail()+"</font>"));
	    	}
	        app.addLink(new HTML(result.getReturnUrl()));
	        */
	      }
	      
	      public void onFailure(Throwable caught) {
	        Window.alert("Error getSajuBanner");
	      }
	    });
	  
  }
  
  
  /**
   * Create the main links at the top of the application.
   
   */
  private void setupMainLinks() {
    // Link to GWT Homepage
    app.addLink(new HTML("<a href=\"" + constants.mainLinkHomepageUrl() + "\">"
        + constants.mainLinkHomepage() + "</a>"));

    // Link to More Examples
    app.addLink(new HTML("<a href=\"" + constants.mainLinkExamplesUrl() + "\">"
        + constants.mainLinkExamples() + "</a>"));
    
    // login, logout
    //app.addLink(new HTML("<a href=\"" + constants.mainLinkExamplesUrl() + "\">로그인</a>"));
    rpcService.getLoginInfo(Window.Location.getPath(), new AsyncCallback<MemberBean>() {
	      public void onSuccess(MemberBean result) {
	    	if(result.getEmail()!=null && result.getEmail().length()>0){ 
	    		app.addLink(new HTML("<font style=\"color:#2D8F26;\">"+result.getEmail()+"</font>"));
	    	}
	        app.addLink(new HTML(result.getReturnUrl()));
	      }
	      
	      public void onFailure(Throwable caught) {
	        Window.alert("Error getLoginInfo");
	      }
	    });
  }
  
  
  /**
   * Create the options that appear next to the title.
   */
  private void setupOptionsPanel() {
    VerticalPanel vPanel = new VerticalPanel();
    vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
    if (LocaleInfo.getCurrentLocale().isRTL()) {
      vPanel.getElement().setAttribute("align", "left");
    } else {
      vPanel.getElement().setAttribute("align", "right");
    }
    app.setOptionsWidget(vPanel);

    // Add the option to change the locale
    final ListBox localeBox = new ListBox();
    String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName();
    if (currentLocale.equals("default")) {
      currentLocale = "en";
    }
    String[] localeNames = LocaleInfo.getAvailableLocaleNames();
    for (String localeName : localeNames) {
      if (!localeName.equals("default")) {
        String nativeName = LocaleInfo.getLocaleNativeDisplayName(localeName);
        localeBox.addItem(nativeName, localeName);
        if (localeName.equals(currentLocale)) {
          localeBox.setSelectedIndex(localeBox.getItemCount() - 1);
        }
      }
    }
    localeBox.addChangeHandler(new ChangeHandler() {
      public void onChange(ChangeEvent event) {
        String localeName = localeBox.getValue(localeBox.getSelectedIndex());
        UrlBuilder builder = Location.createUrlBuilder().setParameter("locale",
            localeName);
        Window.Location.replace(builder.buildString());
      }
    });
    HorizontalPanel localeWrapper = new HorizontalPanel();
    localeWrapper.add(new Image(images.locale()));
    localeWrapper.add(localeBox);
    vPanel.add(localeWrapper);

    // Add the option to change the style
    final HorizontalPanel styleWrapper = new HorizontalPanel();
    vPanel.add(styleWrapper);
    /*
    for (int i = 0; i < ShowcaseConstants.STYLE_THEMES.length; i++) {
      final ThemeButton button = new ThemeButton(
          ShowcaseConstants.STYLE_THEMES[i]);
      styleWrapper.add(button);
      button.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
          // Update the current theme
          CUR_THEME = button.getTheme();

          // Reload the current tab, loading the new theme if necessary
          TabBar bar = ((TabBar) app.getContentTitle());
          bar.selectTab(bar.getSelectedTab());

          // Load the new style sheets
          updateStyleSheets();
        }
      });
    }
    */
  }

  
  
  
//결과창 보여줌
  public void showDetailSaju(){
	 
  		DialogBox dialogBox =  createDialogBoxDetailSaju();
  		//System.out.println("333");
		dialogBox.setAnimationEnabled(true);
		dialogBox.setGlassEnabled(true);
		dialogBox.center();
        dialogBox.show();
  }  
  
  
  
  //시간인덱스를  1~3시 등으로 변환
  private String convertIndexToTime(int currentTimeInt){
    String currentTimeStr="";
    if(currentTimeInt==0){
		  currentTimeStr="23~1시";
	  }else if(currentTimeInt==1){
		  currentTimeStr="1~3시";
	  }else if(currentTimeInt==2){
		  currentTimeStr="3~5시";
	  }else if(currentTimeInt==3){
		  currentTimeStr="5~7시";
	  }else if(currentTimeInt==4){
		  currentTimeStr="7~9시";
	  }else if(currentTimeInt==5){
		  currentTimeStr="9~11시";
	  }else if(currentTimeInt==6){
		  currentTimeStr="11~13시";
	  }else if(currentTimeInt==7){
		  currentTimeStr="13~15시";
	  }else if(currentTimeInt==8){
		  currentTimeStr="15~17시";
	  }else if(currentTimeInt==9){
		  currentTimeStr="17~19시";
	  }else if(currentTimeInt==10){
		  currentTimeStr="19~21시";
	  }else if(currentTimeInt==11){
		  currentTimeStr="21~23시";
	  }
    
    return currentTimeStr;
  }
  
  
  /**
   * 테스트 결과를 보여준다.
   *
   * @return the new dialog box
   */
  private DialogBox createDialogBoxDetailSaju() {
	  
	  

    
    final DialogBox dialogBox = new DialogBox();
    //dialogBox.ensureDebugId("cwDialogBox");
    
    
    
    
    dialogBox.setText("사주 세부정보");
   
    //dialogBox.setPixelSize(550, 570);
    
    // Create a table to layout the content
    VerticalPanel dialogContents = new VerticalPanel();
    //dialogContents.setSpacing(5);
    dialogBox.setWidget(dialogContents);

    

    //////////////////////////////////////////////////////////
    //결과 top Row 컨테이너
    FlexTable resultContainer = new FlexTable();
    resultContainer.addStyleName("resultContainer");
    
  
    
    //내 생년월일시
    final FlexTable mySajuBirth = new FlexTable();
    mySajuBirth.setHTML(0, 0, "생년일시 : ");

    //resultContainer.setWidget(0, 0, mySajuBirth);


    //내 사주결과
    final FlexTable myResultSajuTable = new FlexTable();
    myResultSajuTable.addStyleName("resultSajuTable");

    //myResultSajuTable.setVisible(false);//처음에 않보이게
    
    final Grid mySajuInfo = new Grid(4,3);
    mySajuInfo.addStyleName("sajuInfo");
    
    
    final FlexTable mySajuShortInfo = new FlexTable();
    mySajuShortInfo.addStyleName("sajuShortInfo");
    
    mySajuShortInfo.setHTML(0, 0, "&nbsp");
    mySajuShortInfo.getCellFormatter().setStyleName(0, 0, "ohangCnt");
    mySajuShortInfo.setHTML(0, 1, "&nbsp");
    mySajuShortInfo.getCellFormatter().setStyleName(0, 1, "percent");
    mySajuShortInfo.setHTML(1, 0, "&nbsp");
    mySajuShortInfo.getCellFormatter().setStyleName(1, 0, "yoyak");
    FlexCellFormatter  cellFormatter = mySajuShortInfo.getFlexCellFormatter();
    cellFormatter.setRowSpan(0, 0, 2);

    
    myResultSajuTable.setWidget(0, 0, mySajuInfo);
    myResultSajuTable.setWidget(0, 1, mySajuShortInfo);
    myResultSajuTable.getCellFormatter().setStyleName(0, 1, "resultSajuZeroOne");//오른쪽 정렬을 위해
   

    
    //VerticalPanel contentsPanel= new  VerticalPanel();
    //contentsPanel.add(inputSajuTable);
    
    
    
    // Show the loading image
    /*
    if (loadingImage == null) {
      loadingImage = "<img src=\"" + GWT.getModuleBaseURL()
          + "images/loading.gif\">";
    }
    
    loadingImg = new HTML(loadingImage);
    loadingImg.setVisible(false);
    */
    
    FlexTable myContentTable = new FlexTable();
    myContentTable.setWidget(0, 0, mySajuBirth);//생년월일 입력부분
    myContentTable.setWidget(1, 0, myResultSajuTable);//사주 결과부분

    //contentTable.setWidget(3, 0, loadingImg);//사주 결과부분
    
    resultContainer.setWidget(0, 0, myContentTable);
   
    
 
    
    
    //현재 생년월일시
    final FlexTable currentSajuBirth = new FlexTable();
    currentSajuBirth.setHTML(0, 0, "생년일시 : ");

    //resultContainer.setWidget(0, 1, currentSajuBirth);


    //현재 사주결과
    FlexTable currentResultSajuTable = new FlexTable();
    currentResultSajuTable.addStyleName("resultSajuTable");

    //currentResultSajuTable.setVisible(false);//처음에 않보이게
    
    final Grid currentSajuInfo = new Grid(4,3);
    currentSajuInfo.addStyleName("sajuInfo");
    
    
    final FlexTable currentSajuShortInfo = new FlexTable();
    currentSajuShortInfo.addStyleName("sajuShortInfo");
    
    currentSajuShortInfo.setHTML(0, 0, "&nbsp");
    currentSajuShortInfo.getCellFormatter().setStyleName(0, 0, "ohangCnt");
    currentSajuShortInfo.setHTML(0, 1, "&nbsp");
    currentSajuShortInfo.getCellFormatter().setStyleName(0, 1, "percent");
    currentSajuShortInfo.setHTML(1, 0, "&nbsp");
    currentSajuShortInfo.getCellFormatter().setStyleName(1, 0, "yoyak");
    cellFormatter = currentSajuShortInfo.getFlexCellFormatter();
    cellFormatter.setRowSpan(0, 0, 2);

    
    currentResultSajuTable.setWidget(0, 0, currentSajuInfo);
    currentResultSajuTable.setWidget(0, 1, currentSajuShortInfo);
    currentResultSajuTable.getCellFormatter().setStyleName(0, 1, "resultSajuZeroOne");//오른쪽 정렬을 위해
   

    
    //VerticalPanel contentsPanel= new  VerticalPanel();
    //contentsPanel.add(inputSajuTable);
    
    
    
    // Show the loading image
    /*
    if (loadingImage == null) {
      loadingImage = "<img src=\"" + GWT.getModuleBaseURL()
          + "images/loading.gif\">";
    }
    
    loadingImg = new HTML(loadingImage);
    loadingImg.setVisible(false);
    */
    
    FlexTable currentContentTable = new FlexTable();
    currentContentTable.setWidget(0, 0, currentSajuBirth);//생년월일 입력부분
    currentContentTable.setWidget(1, 0, currentResultSajuTable);//사주 결과부분

    //contentTable.setWidget(3, 0, loadingImg);//사주 결과부분
    
    resultContainer.setWidget(0, 1, currentContentTable);
    
    ////////////////////////////////////////////////////////////////////////
    
    
    
    
    
    
    
    ///////////////////////////////////////////////////////
    //2row 부분
    FlexTable resultContainer2 = new FlexTable();
    
    resultContainer2.addStyleName("resultContainer2");
    
    //1. 오행
    final FlexTable ohhangInfo = new FlexTable();
    ohhangInfo.addStyleName("ohhangInfo");
    
    ohhangInfo.setHTML(0, 0, "&nbsp;");
    
    resultContainer2.setWidget(0, 0, ohhangInfo);
    
    
   //2. 합
    final FlexTable habInfo = new FlexTable();
    habInfo.addStyleName("habInfo");
    
    habInfo.setHTML(0, 0, "해묘미");
    habInfo.setHTML(1, 0, "인오술");
    habInfo.setHTML(2, 0, "사유축");
    habInfo.setHTML(3, 0, "신자진");
    
    habInfo.setHTML(0, 1, "&nbsp;");
    habInfo.setHTML(1, 1, "&nbsp;");
    habInfo.setHTML(2, 1, "&nbsp;");
    habInfo.setHTML(3, 1, "&nbsp;");

    resultContainer2.setWidget(0, 1, habInfo);
    
    
   //3. 살
    final FlexTable salInfo = new FlexTable();
    salInfo.setStyleName("salInfo");
    
    salInfo.setHTML(0, 0, "자미");
    salInfo.setHTML(1, 0, "축오");
    salInfo.setHTML(2, 0, "인유");
    salInfo.setHTML(3, 0, "묘신");
    salInfo.setHTML(4, 0, "진해");
    salInfo.setHTML(5, 0, "사술");
    
    
    
    
    salInfo.setHTML(0, 1, "&nbsp;");
    salInfo.setHTML(1, 1, "&nbsp;");
    salInfo.setHTML(2, 1, "&nbsp;");
    salInfo.setHTML(3, 1, "&nbsp;");
    salInfo.setHTML(4, 1, "&nbsp;");
    salInfo.setHTML(5, 1, "&nbsp;");

    resultContainer2.setWidget(0, 2, salInfo);
    
    
    //4. 총점, 음양비율, 일천간 합,충, 불혼개폐살
    final FlexTable gitaInfo = new FlexTable();
    gitaInfo.setStyleName("gitaInfo");
    
    
    gitaInfo.setHTML(0, 0, "음양");
    gitaInfo.setHTML(1, 0, "일천간합");
    gitaInfo.setHTML(2, 0, "일천간충");
    gitaInfo.setHTML(3, 0, "불혼개폐살");
    gitaInfo.setHTML(4, 0, "총점");
    
    
    
    
    
    gitaInfo.setHTML(0, 1, "&nbsp;");
    gitaInfo.setHTML(1, 1, "&nbsp;");
    gitaInfo.setHTML(2, 1, "&nbsp;");
    gitaInfo.setHTML(3, 1, "&nbsp;");
    gitaInfo.setHTML(4, 1, "&nbsp;");
    
    resultContainer2.setWidget(0, 3, gitaInfo);
    
    dialogContents.add(resultContainer);
    dialogContents.add(resultContainer2);
    
    
    

 
    
    //System.out.println("555");
    // Add a close button at the bottom of the dialog
    Button closeButton = new Button(
        "닫기", new ClickHandler() {
          public void onClick(ClickEvent event) {
            dialogBox.hide();
            //showInsertBirth();
          }
        });
    dialogContents.add(closeButton);
    
    if (LocaleInfo.getCurrentLocale().isRTL()) {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_LEFT);

    } else {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_RIGHT);
    }
	
  
    
    
    //서버에서 사주정보들을 가져온다.
    rpcService.getMyCurrentDetailSajuResult(Window.Location.getPath(), new AsyncCallback<HashMap<String,Object>>() {
	      public void onSuccess(HashMap<String,Object> result) {
	    	  SajuDataTable mySaju=(SajuDataTable)result.get("mySaju");
	    	  SajuDataTable currentSaju=(SajuDataTable)result.get("currentSaju");
	    	  SajuDataTable plusSaju=(SajuDataTable)result.get("plusSaju");
	    	  
	    	  //내 사주 셋팅
	    	  //생년월일시
	    	  
	    	  mySajuBirth.setHTML(0, 0, "생년월일시 : "+mySaju.getSolar_year()+"년 "+mySaju.getSolar_month()+"월 "+mySaju.getSolar_date()+"일 "+convertIndexToTime(Integer.parseInt(mySaju.getBirth_time())));
	    	  
	    	  //사주팔자 
	    	  mySajuInfo.setText(0, 0, mySaju.getYearSkyVal()+mySaju.getYearLandVal());
	    	  mySajuInfo.setText(1, 0, mySaju.getMonthSkyVal()+mySaju.getMonthLandVal());
	    	  mySajuInfo.setText(2, 0, mySaju.getDateSkyVal()+mySaju.getDateLandVal());
	    	  mySajuInfo.setText(3, 0, mySaju.getTimeSkyVal()+mySaju.getTimeLandVal());
	    	  
	    	  
	    	  //오행
	    	  mySajuInfo.setText(0, 1, mySaju.getYearSky5hang()+mySaju.getYearLand5hang());
	    	  mySajuInfo.setText(1, 1, mySaju.getMonthSky5hang()+mySaju.getMonthLand5hang());
	    	  mySajuInfo.setText(2, 1, mySaju.getDateSky5hang()+mySaju.getDateLand5hang());
	    	  mySajuInfo.setText(3, 1, mySaju.getTimeSky5hang()+mySaju.getTimeLand5hang());
	    	  
	    	  // +, -
	    	  mySajuInfo.setText(0, 2, mySaju.getYearSkyPM()+mySaju.getYearLandPM());
	    	  mySajuInfo.setText(1, 2, mySaju.getMonthSkyPM()+mySaju.getMonthLandPM());
	    	  mySajuInfo.setText(2, 2, mySaju.getDateSkyPM()+mySaju.getDateLandPM());
	    	  mySajuInfo.setText(3, 2, mySaju.getTimeSkyPM()+mySaju.getTimeLandPM());
	    	  
	    	  //오행 갯수
	    	  int[] onhangCntCur = mySaju.getOhhangCnt();
	    	  mySajuShortInfo.setHTML(0, 0, "木 "+onhangCntCur[0]+"<br>"+"火 "+onhangCntCur[1]+"<br>"+"土 "+onhangCntCur[2]+"<br>"+"金 "+onhangCntCur[3]+"<br>"+"水 "+onhangCntCur[4]);
	    	  
	    	  //음양 비율
	    	  mySajuShortInfo.setText(0, 1, "음 "+mySaju.getMinusPercent()+" 양 "+mySaju.getPlusPercent());
	    	  
	    	  //간단한 설명
	    	  mySajuShortInfo.setText(1, 0, mySaju.getYoyakDesc());
	    	  
	    	  
	    	  
	    	  
	    	  
	    	  //현재사주 셋팅
	    	  
	    	  //생년월일시
	    	  
	    	  currentSajuBirth.setHTML(0, 0, "현재 년월일시 : "+currentSaju.getSolar_year()+"년 "+currentSaju.getSolar_month()+"월 "+currentSaju.getSolar_date()+"일 "+convertIndexToTime(Integer.parseInt(currentSaju.getBirth_time())));
	    	  
	    	  //사주팔자 
	    	  currentSajuInfo.setText(0, 0, currentSaju.getYearSkyVal()+currentSaju.getYearLandVal());
	    	  currentSajuInfo.setText(1, 0, currentSaju.getMonthSkyVal()+currentSaju.getMonthLandVal());
	    	  currentSajuInfo.setText(2, 0, currentSaju.getDateSkyVal()+currentSaju.getDateLandVal());
	    	  currentSajuInfo.setText(3, 0, currentSaju.getTimeSkyVal()+currentSaju.getTimeLandVal());
	    	  
	    	  
	    	  //오행
	    	  currentSajuInfo.setText(0, 1, currentSaju.getYearSky5hang()+currentSaju.getYearLand5hang());
	    	  currentSajuInfo.setText(1, 1, currentSaju.getMonthSky5hang()+currentSaju.getMonthLand5hang());
	    	  currentSajuInfo.setText(2, 1, currentSaju.getDateSky5hang()+currentSaju.getDateLand5hang());
	    	  currentSajuInfo.setText(3, 1, currentSaju.getTimeSky5hang()+currentSaju.getTimeLand5hang());
	    	  
	    	  // +, -
	    	  currentSajuInfo.setText(0, 2, currentSaju.getYearSkyPM()+currentSaju.getYearLandPM());
	    	  currentSajuInfo.setText(1, 2, currentSaju.getMonthSkyPM()+currentSaju.getMonthLandPM());
	    	  currentSajuInfo.setText(2, 2, currentSaju.getDateSkyPM()+currentSaju.getDateLandPM());
	    	  currentSajuInfo.setText(3, 2, currentSaju.getTimeSkyPM()+currentSaju.getTimeLandPM());
	    	  
	    	  //오행 갯수
	    	  int[] onhangCntMy = currentSaju.getOhhangCnt();
	    	  currentSajuShortInfo.setHTML(0, 0, "木 "+onhangCntMy[0]+"<br>"+"火 "+onhangCntMy[1]+"<br>"+"土 "+onhangCntMy[2]+"<br>"+"金 "+onhangCntMy[3]+"<br>"+"水 "+onhangCntMy[4]);
	    	  
	    	  //음양 비율
	    	  currentSajuShortInfo.setText(0, 1, "음 "+currentSaju.getMinusPercent()+" 양 "+currentSaju.getPlusPercent());
	    	  
	    	  //간단한 설명
	    	  currentSajuShortInfo.setText(1, 0, currentSaju.getYoyakDesc());
	    	  
	    	  
	    	  ////////////////////////////////////////////
	    	  // 내사주, 현재사주 합친 사주
	    	 
	    	  //오행 갯수
	    	  float[] onhangCntAvg = plusSaju.getOhhangCntAvg();
	    	  ohhangInfo.setHTML(0, 0, "木 "+onhangCntAvg[0]+"<br>"+"火 "+onhangCntAvg[1]+"<br>"+"土 "+onhangCntAvg[2]+"<br>"+"金 "+onhangCntAvg[3]+"<br>"+"水 "+onhangCntAvg[4]);
	    	  
	    	  //합 갯수
	    	  habInfo.setHTML(0, 1, Integer.toString(plusSaju.getMokPlus()));
	    	  habInfo.setHTML(1, 1, Integer.toString(plusSaju.getWhaPlus()));
	    	  habInfo.setHTML(2, 1, Integer.toString(plusSaju.getGeumPlus()));
	    	  habInfo.setHTML(3, 1, Integer.toString(plusSaju.getSuPlus()));
	    	  
	    	  //살 갯수
	    	  salInfo.setHTML(0, 1, Integer.toString(plusSaju.getJamiMinus()));
	    	  salInfo.setHTML(1, 1, Integer.toString(plusSaju.getChukohMinus()));
	    	  salInfo.setHTML(2, 1, Integer.toString(plusSaju.getInyuMinus()));
	    	  salInfo.setHTML(3, 1, Integer.toString(plusSaju.getMyosinMinus()));
	    	  salInfo.setHTML(4, 1, Integer.toString(plusSaju.getJinhaeMinus()));
	    	  salInfo.setHTML(5, 1, Integer.toString(plusSaju.getSasulMinus()));
	    	  
	    	//기타 정보
	    	  gitaInfo.setHTML(0, 1, "음  "+Integer.toString(plusSaju.getMinusPercent())+"양  "+Integer.toString(plusSaju.getPlusPercent()));
	    	  String skyHab="";
	    	  if(plusSaju.getSkyHab().length()==2){
	    		  skyHab=plusSaju.getSkyHab();
	    	  }else{
	    		  skyHab="X";
	    	  }
	    	  gitaInfo.setHTML(1, 1, skyHab);
	    	  String skyChung="";
	    	  if(plusSaju.getSkyChung().length()==2){
	    		  skyChung=plusSaju.getSkyChung();
	    	  }else{
	    		  skyChung="X";
	    	  }
	    	  gitaInfo.setHTML(2, 1, skyChung);
	    	  String neverMarriage="";
	    	  if(plusSaju.isNeverMarriage()){
	    		  neverMarriage="O";
	    	  }else{
	    		  neverMarriage="X";
	    	  }
	    	  gitaInfo.setHTML(3, 1, neverMarriage);
	    	  gitaInfo.setHTML(4, 1, Integer.toString(plusSaju.getTotalScore()));
	      }
	      
	      public void onFailure(Throwable caught) {
	        Window.alert("Error getMyCurrentDetailSajuResult");
	      }
	    });
    
    
    // Return the dialog box
    return dialogBox;
  }
  
  
 
  
  
//생년월일 입력
  public void showInsertBirth(){
	 
  		DialogBox dialogBox =  createDialogBoxBirth();
  		//System.out.println("333");
		dialogBox.setAnimationEnabled(true);
		dialogBox.setGlassEnabled(true);
		dialogBox.center();
        dialogBox.show();
  }  
  
  
  
  /**
   * 생년월일 입력
   *
   * @return the new dialog box
   */
  private DialogBox createDialogBoxBirth() {
	  
	  

    
    final DialogBox dialogBox = new DialogBox();
    //dialogBox.ensureDebugId("cwDialogBox");
    
    
    
    
    dialogBox.setText("생년월일시 입력");
   
    //dialogBox.setPixelSize(250, 70);
    
    // Create a table to layout the content
    VerticalPanel dialogContents = new VerticalPanel();
    dialogContents.setSpacing(5);
    dialogBox.setWidget(dialogContents);

    
    //생년월일시 입력부분
    FlexTable inputSajuTable = new FlexTable();
    inputSajuTable.addStyleName("inputSajuTable");
    
    inputSajuTable.setHTML(0, 0, "생일입력");
    inputSajuTable.getCellFormatter().addStyleName(0, 0, "inputSajuHeader");
    inputSajuTable.setHTML(0, 1, "시간입력");
    inputSajuTable.getCellFormatter().addStyleName(0, 1, "inputSajuHeader");
    inputSajuTable.setHTML(0, 2, "성별");
    inputSajuTable.getCellFormatter().addStyleName(0, 2, "inputSajuHeader");
    inputSajuTable.setHTML(0, 3, "직업");
    inputSajuTable.getCellFormatter().addStyleName(0, 3, "inputSajuHeader");
    inputSajuTable.setHTML(0, 4, "사는곳");
    inputSajuTable.getCellFormatter().addStyleName(0, 4, "inputSajuHeader");
    
    
    Button btnConfirm = new Button("저장");
    inputSajuTable.setWidget(0, 5, btnConfirm);
    inputSajuTable.getCellFormatter().addStyleName(0, 5, "inputSajuConfirm");
    HorizontalPanel birthPanel = new HorizontalPanel();
    
    birthPanel.add(new Label("양력 "));
    //dateBox = new DateBox();
    //yearTxt = new TextBox();
    //yearTxt.setMaxLength(4);
    //yearTxt.setSize("45px","20px");
    final ListBox yearBox = new ListBox();
    for (int i = 1881, j=0; i < 2050; i++,j++) {
    	yearBox.addItem(Integer.toString(i));
    	yearBox.setValue(j, Integer.toString(i));
    }
    yearBox.setItemSelected(100, true);//default 1981년 선택
    
    //monthTxt = new TextBox();
    //monthTxt.setMaxLength(2);
    //monthTxt.setSize("25px","20px");
    final ListBox monthBox = new ListBox();
    for (int i = 1, j=0; i < 13; i++,j++) {
    	monthBox.addItem(Integer.toString(i));
    	monthBox.setValue(j, Integer.toString(i));
    }
    
    //dateTxt = new TextBox();
    //dateTxt.setMaxLength(2);
    //dateTxt.setSize("25px","20px");
    final ListBox dateBox = new ListBox();
    for (int i = 1, j=0; i < 32; i++,j++) {
    	dateBox.addItem(Integer.toString(i));
    	dateBox.setValue(j, Integer.toString(i));
    }
    
    birthPanel.add(yearBox);
    birthPanel.add(new HTML("년 "));
    birthPanel.add(monthBox);
    birthPanel.add(new HTML("월 "));
    birthPanel.add(dateBox);
    birthPanel.add(new HTML("일"));
    
    inputSajuTable.setWidget(1, 0, birthPanel);
    inputSajuTable.getCellFormatter().addStyleName(1, 0, "inputSajuBirth");
    
    final ListBox timeBox = new ListBox();
    String[] listTypes = constants.sajuTimeDatas();
    for (int i = 0; i < listTypes.length; i++) {
    	timeBox.addItem(listTypes[i]);
    	timeBox.setValue(i, Integer.toString(i));//값을 0~11로 설정(23~1시(0), 1~3시(1)...)
    }
    inputSajuTable.setWidget(1, 1, timeBox);
    inputSajuTable.getCellFormatter().addStyleName(1, 1, "inputSajuBirth");
    
    
    final ListBox sexBox = new ListBox();
    String[] sexTypes = constants.sexDatas();
    for (int i = 0; i < sexTypes.length; i++) {
    	sexBox.addItem(sexTypes[i]);
    	sexBox.setValue(i, Integer.toString(i+1));//남자1, 여자2
    }
    inputSajuTable.setWidget(1, 2, sexBox);
    inputSajuTable.getCellFormatter().addStyleName(1, 2, "inputSajuBirth");
    
    
    
    final ListBox jobBox = new ListBox();
    String[] jobs = constants.jobs();
    for (int i = 0; i < jobs.length; i++) {
    	jobBox.addItem(jobs[i]);
    	jobBox.setValue(i, jobs[i]);//남자1, 여자2
    }
    
    inputSajuTable.setWidget(1, 3, jobBox);
    inputSajuTable.getCellFormatter().addStyleName(1, 3, "inputSajuBirth");
    
    
    final ListBox addrBox = new ListBox();
    String[] addrSido = constants.addrSido();
    for (int i = 0; i < addrSido.length; i++) {
    	addrBox.addItem(addrSido[i]);
    	addrBox.setValue(i, addrSido[i]);//남자1, 여자2
    }
    inputSajuTable.setWidget(1, 4, addrBox);
    inputSajuTable.getCellFormatter().addStyleName(1, 4, "inputSajuBirth");
    
    
    FlexCellFormatter cellFormatter = inputSajuTable.getFlexCellFormatter();
    cellFormatter.setRowSpan(0, 5, 2);
    
    dialogContents.add(inputSajuTable);
    
    
    final HTML resultText = new HTML("&nbsp;");
    dialogContents.add(resultText);
    
    
    btnConfirm.addClickHandler(new ClickHandler() {   
	      public void onClick(ClickEvent event) {
	    	  
	    	    	  
	    	  rpcService.saveSajuResult(yearBox.getValue(yearBox.getSelectedIndex()), monthBox.getValue(monthBox.getSelectedIndex()), dateBox.getValue(dateBox.getSelectedIndex()), timeBox.getValue(timeBox.getSelectedIndex()), sexBox.getValue(sexBox.getSelectedIndex()), jobBox.getValue(jobBox.getSelectedIndex()), addrBox.getValue(addrBox.getSelectedIndex()), new AsyncCallback<String>() {
	    	      public void onSuccess(String result) {
	    	        //display.setSajuResult(result);
	    	    	  resultText.setHTML("저장되었습니다.");
	    	    	  refreshSajuInfo();
	    	    	  dialogBox.hide();
	    	    	  History.newItem("search_friend");
	    	      }
	    	      
	    	      public void onFailure(Throwable caught) {
	    	        Window.alert("Error saveSajuResult");
	    	      }
	    	    });
	      }
	    });
    
   
    
    
    
    
    
    
   
    
    
    

 
    
    //System.out.println("555");
    // Add a close button at the bottom of the dialog
    Button closeButton = new Button(
        "닫기", new ClickHandler() {
          public void onClick(ClickEvent event) {
            dialogBox.hide();
           
          }
        });
    dialogContents.add(closeButton);
    
    if (LocaleInfo.getCurrentLocale().isRTL()) {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_LEFT);

    } else {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_RIGHT);
    }
	
    // Return the dialog box
    return dialogBox;
  }
  
  
  
  
//결과창 보여줌
  public void showSearchFriendResult(List<FriendTable> result){
	 
  		DialogBox dialogBox =  createDialogBox(result);
  		//System.out.println("333");
		dialogBox.setAnimationEnabled(true);
		dialogBox.setGlassEnabled(true);
		dialogBox.center();
        dialogBox.show();
  }  
  
  
  
  /**
   * 친구찾기
   *
   * @return the new dialog box
   */
  private DialogBox createDialogBox(List<FriendTable> result) {
	  
	  

    
    final DialogBox dialogBox = new DialogBox();
    //dialogBox.ensureDebugId("cwDialogBox");
    
    
    
    
    dialogBox.setText("친구 찾기");
   
    //dialogBox.setPixelSize(250, 70);
    
    // Create a table to layout the content
    VerticalPanel dialogContents = new VerticalPanel();
    dialogContents.setSpacing(5);
    dialogBox.setWidget(dialogContents);

    
    ////////////////////////////////////////////
    /*
    Grid grid = new Grid(result.getQuestionNumForType()+1, 10);
    for(int i=1;i<=9;i++){
    	 grid.setWidget(0, i, new HTML(i+"유형"));
    }
    
    for(int i=1;i<=result.getQuestionNumForType();i++){
   	 grid.setWidget(i, 0, new HTML(Integer.toString(i)+"번"));
   }
   
    
    for(int i=1;i<=result.getQuestionNumForType();i++){
    	for(int j=1;j<=9;j++){
    		String resultTxt="";
    		if(result.isSelectedAgree(j,i)){
    			resultTxt="동의";
    		}else if(result.isSelectedMedi(j,i)){
    			resultTxt="보통";
    		}else if(result.isSelectedRej(j,i)){
    			resultTxt="반대";
    		}
    		grid.setWidget(i, j, new HTML(resultTxt));
    	}
    }
    dialogContents.add(grid);
    dialogContents.setCellHorizontalAlignment(
    		grid, HasHorizontalAlignment.ALIGN_CENTER);
   */
  ////////////////////////////////////////////////////////////
   
    
    // Create a grid
    FlexTable searchFriendTable = new FlexTable();
    
    
    searchFriendTable.setWidget(0, 0, new HTML("순위"));
    searchFriendTable.setWidget(0, 1, new HTML("점수"));
    searchFriendTable.setWidget(0, 2, new HTML("성별"));
    searchFriendTable.setWidget(0, 3, new HTML("채팅"));
    searchFriendTable.setWidget(0, 4, new HTML("이메일"));
    searchFriendTable.setWidget(0, 5, new HTML("사는곳"));
    searchFriendTable.setWidget(0, 6, new HTML("직업"));
    
    searchFriendTable.addStyleName("searchFriendTable");
    searchFriendTable.getRowFormatter().addStyleName(0, "title");
    
    String sex="";
    if(result.size()>0){
	    for (int i=0; i < result.size() && i<10 ;i++) {
	    	FriendTable friend=result.get(i);
	    	searchFriendTable.setWidget(i+1, 0, new HTML(Integer.toString(i+1)));
	    	searchFriendTable.setWidget(i+1, 1, new HTML(Integer.toString(friend.getScore())));
	    	if(friend.getSex().equals("1")){
	    		sex="남";
	    	}else if(friend.getSex().equals("2")){
	    		sex="여";
	    	}
	    	
	    	searchFriendTable.setWidget(i+1, 2, new HTML(sex));
	    	searchFriendTable.setWidget(i+1, 3, new Button("채팅하기"));
	    	searchFriendTable.setWidget(i+1, 4, new Button("이메일 보내기"));
	    	searchFriendTable.setWidget(i+1, 5, new HTML(friend.getAddr1()));
	    	searchFriendTable.setWidget(i+1, 6, new HTML(friend.getJob()));
	    }
	    
	   
    }else{
    	FlexCellFormatter cellFormatter = searchFriendTable.getFlexCellFormatter();
    	cellFormatter.setColSpan(1, 0, 7);
    	searchFriendTable.setWidget(1, 0, new HTML("친구를 찾지 못했습니다."));
    }
   
    
    ////////////////////////////////
  
    dialogContents.add(searchFriendTable);
    ////////////////////////////////
    
    
    

 
    
    //System.out.println("555");
    // Add a close button at the bottom of the dialog
    Button closeButton = new Button(
        "닫기", new ClickHandler() {
          public void onClick(ClickEvent event) {
            dialogBox.hide();
          }
        });
    dialogContents.add(closeButton);
    
    if (LocaleInfo.getCurrentLocale().isRTL()) {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_LEFT);

    } else {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_RIGHT);
    }
	
    // Return the dialog box
    return dialogBox;
  }
  
  
  
  
}
